package SteamDemo02;

import com.sun.javafx.collections.MappingChange;

import java.util.*;
import java.util.stream.Collectors;

public class StreamOperations {

    // 假设有一个 Person 类
    public static class Person {
        private String name;
        private int age;

        // 构造函数、getter 和 setter 方法
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

    public static void main(String[] args) {

        List<Person> people = Arrays.asList(
                new Person("Alice", 30),
                new Person("Bob", 20),
                new Person("Charlie", 25),
                new Person("David", 30),
                new Person("Eve", 20)
        );

        // 1. 过滤对象
     /*   List<Person> adults = new ArrayList<>();
        for (Person person : people) {
            if (person.getAge() >= 18) {
                adults.add(person);
            }
        }
        System.out.println("Adults: " + adults);*/

        List<Person> adults = people.stream().filter(abc -> abc.getAge() > 18).collect(Collectors.toList());
        System.out.println("Adults" + adults);

        // 2. 映射对象属性
       /* List<String> names = new ArrayList<>();
        for (Person person : people) {
            names.add(person.getName());
        }
        System.out.println("Names: " + names);*/

        List<String> name = people.stream().map(Person::getName).collect(Collectors.toList());
        System.out.println("Names" + name);

        // 3. 排序对象
      /*  List<Person> sortedByAge = new ArrayList<>(people);
        Collections.sort(sortedByAge, (p1, p2) -> p1.getAge() - p2.getAge()));

        System.out.println("Sorted by Age: " + sortedByAge);*/

        List<Person> sortedByAge = people.stream()
                .sorted(Comparator.comparing(Person::getAge))
                .collect(Collectors.toList());
        System.out.println("Sorted by Age: " + sortedByAge);

        // 4. 去重对象
    /*    List<Person> distinctPerson = new ArrayList<>();
        HashSet<Person> seen = new HashSet<>();
        for(Person person : people){
             if(person !=null && seen.contains(person)){
                 seen.add(person);
                 distinctPerson.add(person);


             }
        }*/

        List<Person> distinctPerson = people.stream().distinct().collect(Collectors.toList());
        System.out.println("distinctPerson" + distinctPerson);

        //分组对象
   /*     Map<Integer,List<Person>> map = new HashMap<>();
        for(Person person : people){
            int age = person.getAge();
            if(! map.containsKey(age)){
                map.put(age,new ArrayList<>());
            }
            map.get(age).add(person);
        }
*/
        Map<Integer, List<Person>> groupByAge = people.stream().collect(Collectors.groupingBy(Person::getAge));
        System.out.println("groupByAge" + groupByAge);


        // 6. 统计对象数量
       /* List<Person> list = new ArrayList<>();
        int count = 0;
        for(Person person : people){
            count++;
        }
        System.out.println("count:"+count);*/

        long count = people.stream().count();
        System.out.println("count:" + count);

        // 7. 计算最大/最小值
     /*  Person oldest = null;
       for(Person person : people){
           if(oldest!=null || person.getAge()>oldest.getAge());
           oldest=person;

       }
        System.out.println("oldest"+oldest);*/


        Optional<Person> MAX = people.stream().max(Comparator.comparing(Person::getAge));
        System.out.println("MAX" + MAX);

        Optional<Person> MIN = people.stream().min(Comparator.comparing(Person::getAge));
        System.out.println("MIN" + MIN);

        // 8. 连接属性
      /*  StringBuilder sb = new StringBuilder();
        for(Person person : people){
            sb.append(person.getAge());
            if(!sb.toString().isEmpty()){
                sb.append(",");
            }
        }
        String Name = sb.toString();
        System.out.println(Name);
*/
        String Name = people.stream().map(Person::getName).collect(Collectors.joining(","));
        System.out.println("Name" + Name);

        // 9. 合并对象属性
        /*   *//* int TotalAge = 0;
        for(Person person : people){
            Integer age = person.getAge();
            if(age!=null){
                TotalAge+=age;


            }
            System.out.println("TotalAge"+TotalAge);*//*

        }*/

        int TotalAge = people.stream().map(Person::getAge).reduce(0, Integer::sum);
        System.out.println("TotalAge:" + TotalAge);

        // 10. 计算平均值
     /*  int totalAges = 0;
       int counts = 0;
       for(Person person : people){
           Integer age = person.getAge();
           if(age!=null){
               totalAges+=age;
               counts++;
           }


        }
       double averyAge = (double) totalAges/counts;
        System.out.println("averyAge"+averyAge);
*/
        double averyAge = people.stream().mapToInt(Person::getAge).average().orElse(0);
        System.out.println("averAge:"+averyAge);

        // 11. 获取流的第一个元素
/*     if(people==null||people.isEmpty()){
         System.out.println("people is null");
     }
     else {
         Person firstPerson = people.get(0);
         System.out.println("Firstperson"+ firstPerson);

     }
     */
     Optional<Person> firstPerson = people.stream().findFirst();
        System.out.println("Firstperson"+ firstPerson);

        // 12. 获取流的任意一个元素（并行流时有用）
        /*if(people==null||people.isEmpty()){
            System.out.println("people is null");
        }
        else {
            int random = new Random().nextInt(people.size());
            Person randomPerson = people.get(random);
            System.out.println("randomPerson:"+randomPerson);

        }*/

        Optional<Person> anyPerson = people.stream().findAny();
        System.out.println("anyPerson"+anyPerson);

        // 13. 检查是否所有元素匹配条件
       /* boolean allAdults = true;

            if(people==null||people.isEmpty()){
                System.out.println("无");
            }
            else {
                for(Person person : people){
                    Integer age = person.getAge();
                    if(age==null||age<18){
                        allAdults=false;
                        break;

                    }
                }
                System.out.println("allAdults:"+allAdults);
            }
*/
        boolean allAdults = people.stream().allMatch(person -> person.getAge()>=18);
        System.out.println("allAdults"+allAdults);

        // 14. 检查是否有任何元素匹配条件
   /*     boolean anyTeenager = false;
        if(people==null||people.isEmpty()){
            System.out.println("无");
        }
        for(Person person : people){
            Integer age = person.getAge();
            if(age==null||age<20){
                anyTeenager=true;
                break;
            }

        }
        System.out.println("anyTeenager"+anyTeenager);*/

        boolean anyTeenager = people.stream().anyMatch(person -> person.getAge()<20);
        System.out.println("anyTeenager"+anyTeenager);

        // 15. 检查是否没有任何元素匹配条件
     /*   boolean noneWithNegativeAge = true;

        if (people == null || people.isEmpty()) {
            System.out.println("无");
        } else {
            for (Person person : people) {
                Integer age = person.getAge();
                if (age == null || age < 0) {
                    noneWithNegativeAge = false;
                    break;
                }
            }
            System.out.println("noneWithNegativeAge " + noneWithNegativeAge);
        }*/

        boolean noneWithNegativeAge = people.stream().noneMatch(person -> person.getAge()<0);
        System.out.println("noneWithNegativeAge"+noneWithNegativeAge);

        // 16. 映射到一个新的流，并进行收集（例如: 对象到列表的转换）
     /*   List<String> upperCaseNames = new ArrayList<>();
        if (people == null || people.isEmpty()) {
            System.out.println("People list is empty!");
        } else {
            for(Person person : people){
                String names = person.getName();
                if(names==null||){
                    upperCaseNames.add(names.toUpperCase());
                }
            }
            System.out.println(" upperCaseNames:"+upperCaseNames);
        }*/

        List<String> upperCaseNames = people.stream().map(person -> person.getName().toUpperCase()).collect(Collectors.toList());
        System.out.println(" upperCaseNames:"+upperCaseNames);

        // 17. 将流中的元素聚合为一个 Map
     /*   Map<String,Integer> nameToAgeMap = new HashMap<>();
        if(people==null||people.isEmpty()){
            System.out.println("无");
        }
        else {
            for(Person person : people){
                String names = person.getName();
                Integer age = person.getAge();
                if(names!=null||age!=null){
                    nameToAgeMap.put(names,age);

                }
            }
            System.out.println("namrToAgeMap:"+nameToAgeMap);
        }*/

        Map<String,Integer> nameToAgeMap = people.stream().collect(Collectors.toMap(Person::getName,Person::getAge));
        System.out.println("namrToAgeMap:"+nameToAgeMap);

        // 18. 将流中的元素转换为一个 Set
      /*  Set<String> nameSet = new HashSet<>();
        if (people == null || people.isEmpty()) {
            System.out.println("无");
        } else {
            for (Person person : people) {
                String names = person.getName();
                if (name != null) {
                    nameSet.add(names);
                }
            }
        }
        System.out.println("nameSet: " + nameSet);*/

        Set<String> nameSet = people.stream().map(Person::getName).collect(Collectors.toSet());
        System.out.println("nameSet: " + nameSet);

        // 19. 获取流中最大值和最小值（示例：获取最高和最低年龄）
        Optional<Person> maxAge = people.stream().max(Comparator.comparing(Person::getAge));
        System.out.println("maxAge"+maxAge);

        Optional<Person> minAge = people.stream().min(Comparator.comparing(Person::getAge));
        System.out.println("minAge"+minAge);

    }
}